﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using com.google.zxing;
using ByteMatrix = com.google.zxing.common.ByteMatrix;

namespace DoubleH.Utility.Barcode
{
    public class BarcodeUtility
    {
        /// <summary>
        /// 生成中间带图片的二维码
        /// </summary>
        /// <param name="text"></param>
        /// <param name="middlImg"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public Image BuildBarCode2(string text, Image middlImg, int size = 150)
        {
            try
            {
                //构造二维码写码器
                MultiFormatWriter mutiWriter = new com.google.zxing.MultiFormatWriter();
                Hashtable hint = new Hashtable();
                hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
                hint.Add(EncodeHintType.ERROR_CORRECTION, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.H);
                //生成二维码
                ByteMatrix bm = mutiWriter.encode(text, com.google.zxing.BarcodeFormat.QR_CODE, size, size, hint);
                Bitmap img = bm.ToBitmap();
                //获取二维码实际尺寸（去掉二维码两边空白后的实际尺寸）
                System.Drawing.Size realSize = mutiWriter.GetEncodeSize(text, com.google.zxing.BarcodeFormat.QR_CODE, size, size);
                //计算插入图片的大小和位置
                int middleImgW = Math.Min((int)(realSize.Width / 3.5), middlImg.Width);
                int middleImgH = Math.Min((int)(realSize.Height / 3.5), middlImg.Height);
                int middleImgL = (img.Width - middleImgW) / 2;
                int middleImgT = (img.Height - middleImgH) / 2;

                //将img转换成bmp格式，否则后面无法创建 Graphics对象
                Bitmap bmpimg = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                using (Graphics g = Graphics.FromImage(bmpimg))
                {
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    g.DrawImage(img, 0, 0);
                }

                //在二维码中插入图片
                System.Drawing.Graphics MyGraphic = System.Drawing.Graphics.FromImage(bmpimg);
                //白底
                MyGraphic.FillRectangle(Brushes.White, middleImgL, middleImgT, middleImgW, middleImgH);
                MyGraphic.DrawImage(middlImg, middleImgL, middleImgT, middleImgW, middleImgH);

                return bmpimg;
            }
            catch  
            { return null; }
        }
    }
}